package cuit.demo.controller;
import cuit.demo.Entity.User;
import cuit.demo.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RegisterController {

    @Autowired
    private MyService myService;

    // 显示注册页面
    @GetMapping("/register")
    public String showRegistrationForm() {
        return "register";
    }

    // 处理用户注册
    @PostMapping("/register")
    public String registerUser(
            @RequestParam int userid,
            @RequestParam String username,
            @RequestParam String userpwd,
            @RequestParam String usersex,
            @RequestParam String email,
            @RequestParam String phone,
            Model model) {

        // 检查用户名是否已经存在（假设 MyService 中有合适的方法来实现这个检查）
        User existingUser = myService.findUserById(userid);
        if (existingUser!= null) {
            model.addAttribute("error", "用户名已存在，请选择其他用户名！");
            return "register";
        }

        // 创建新用户对象
        User newUser = new User();
        newUser.setUserid(userid);
        newUser.setUsername(username);
        newUser.setUserpwd(userpwd);
        newUser.setUsersex(usersex);
        newUser.setEmail(email);
        newUser.setPhone(phone);

        // 使用 MyService 保存用户
        myService.saveUser(newUser);
        model.addAttribute("message", "注册成功，请登录！");
        return "login";
    }
}